package com.yyaccp.easybuy.security.config;


import com.yyaccp.easybuy.security.service.token.TokenService;
import com.yyaccp.easybuy.security.vo.AuthProperties;
import com.yyaccp.easybuy.security.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class TokenFilter extends OncePerRequestFilter {
    @Resource
    private TokenService tokenService;
    @Autowired
    private AuthProperties authProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = authProperties.getTokenImpl().equals("redis") ? request.getHeader("token") : request.getHeader("Authorization");
        /**
         * 在security鉴权前，根据前端传递的token,从redis或jwt中找回登录的用户和权限
         * 存储到security的context中，供后续鉴权使用
         */
        if(StringUtils.hasText(token)) {
            LoginUser loginUser = tokenService.getLoginUser(token);
            if(Objects.nonNull(loginUser)) {
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser,
                                loginUser.getPassword(), loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
